Public Class ProductItemDialog
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents txtColor As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlPackingNo As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtQuantity As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkFixed As System.Web.UI.WebControls.CheckBox
    Protected WithEvents txtSpecialInstruction As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents ddlBO As System.Web.UI.WebControls.DropDownList
    Protected WithEvents trBO As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents valsValidationSummary As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents reqvProductColor As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtProductCode As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvProductCode As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents lblStatus As System.Web.UI.WebControls.Label
    Protected WithEvents cusvQuantityCheck As System.Web.UI.WebControls.CustomValidator
    Protected WithEvents comvQuantity As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents CompareValidator1 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents hidProductCodeID As System.Web.UI.HtmlControls.HtmlInputHidden    
    Protected WithEvents hidColorID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents dgBOItems As System.Web.UI.WebControls.DataGrid
    Protected WithEvents trProCode As System.Web.UI.HtmlControls.HtmlTableRow    
    Protected WithEvents trProColor As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents regvSI As System.Web.UI.WebControls.RegularExpressionValidator
    Protected WithEvents trPartofBarCode As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents txtPartOfBarcode As System.Web.UI.WebControls.TextBox
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Const EXISTING_TEXT As String = "Your selected product code & color are already existed.<br>Please select another product code/color"

#Region "   Properties"
    Protected ReadOnly Property PageBO() As COrder
        Get
            If IsNothing(Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME)) Then
                Throw New ApplicationException("Session expried. Please re-login")
            End If
            Return CType(Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME), COrder)
        End Get
    End Property

    Private Property OrderItemIndex() As Integer
        Get
            Return CInt(ViewState("OrderItemIndex"))
        End Get
        Set(ByVal Value As Integer)
            ViewState("OrderItemIndex") = Value
        End Set
    End Property

    Protected ReadOnly Property OrderItem() As COrderItem
        Get
            Return PageBO.OrderItem(OrderItemIndex)
        End Get
    End Property

    Protected ReadOnly Property CustomerID() As Integer
        Get
            Return CInt(Request.QueryString("cid"))
        End Get
    End Property
#End Region

    Private Sub UpdateData(ByVal bSave As Boolean)
        If bSave Then
            With OrderItem

                If trBO.Visible = True Then
                    Try
                        Dim dgi As DataGridItem
                        For Each dgi In dgBOItems.Items
                            Dim rad As HtmlInputRadioButton
                            rad = CType(dgi.Cells(0).FindControl("rdbSelected"), HtmlInputRadioButton)

                            If rad.Checked Then
                                .UseFromBoItem = CInt(rad.Value)
                                Exit For
                            End If
                        Next
                    Catch
                    End Try
                End If

                If .UseFromBoItem > 0 Then
                    Dim objOI As New COrderItem
                    objOI.Load(.UseFromBoItem)
                    .ColorLkdID = objoi.ColorLkdID
                    .ProductCodeID = objoi.ProductCodeID
                Else
                    If (Me.hidColorID.Value.Length > 0) Then
                        .ColorLkdID = CInt(Me.hidColorID.Value)
                    Else
                        .ColorLkdID = Nothing
                    End If
                    .ProductCodeID = CInt(Me.hidProductCodeID.Value)
                End If

                .Quantity = CInt(Me.txtQuantity.Text)
                .SpecialInstructions = Me.txtSpecialInstruction.Text
                .Packing = CByte(Me.ddlPackingNo.SelectedItem.Text)
                .IsFixed = Me.chkFixed.Checked
            End With
        Else
            With OrderItem
                If .UseFromBoItem > 0 Then
                    Try
                        Dim objOI As New COrderItem
                        objOI.Load(.UseFromBoItem)
                        Me.ddlBO.SelectedIndex = Me.ddlBO.Items.IndexOf(ddlBO.Items.FindByValue(objOI.OrderId.ToString))
                    Catch ex As Exception
                        Me.ddlBO.SelectedIndex = 0
                    End Try
                End If

                Me.hidColorID.Value = .ColorLkdID.ToString                
                Me.hidProductCodeID.Value = .ProductCodeID.ToString

                Me.txtColor.Text = .Color                
                Me.txtProductCode.Text = .ProductCode
                Me.txtPartOfBarcode.Text = .ProductCodeTable.PartOfBarcode

                Me.txtQuantity.Text = .Quantity.ToString
                Me.txtSpecialInstruction.Text = .SpecialInstructions
                Me.chkFixed.Checked = .IsFixed

                Try
                    Me.ddlPackingNo.SelectedIndex = Me.ddlPackingNo.Items.IndexOf(ddlPackingNo.Items.FindByValue(.Packing.ToString))
                Catch
                    ddlPackingNo.SelectedIndex = 0
                End Try

                Me.BindGrid()
            End With
        End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            Dim idx As Integer
            idx = CInt(Request.QueryString("idx"))

            Dim type As EOrderType
            type = CType(Request.QueryString("type"), EOrderType)

            Dim OIType As EOrderItemType
            OIType = CType(Request.QueryString("oitype"), EOrderItemType)

            If type = EOrderType.Purchase_Order Then

                If OIType = EOrderItemType.Use_from_BO_only Then
                    Dim dt As DataTable
                    dt = COrder.GetAllBulkOrder
                    Me.ddlBO.DataSource = dt
                    Me.ddlBO.DataTextField = "ORDER_NUMBER"
                    Me.ddlBO.DataValueField = "ORDER_ID_PK"
                    Me.ddlBO.DataBind()

                    Me.BindGrid()
                Else
                    Me.trBO.Visible = False
                End If


                'Dim i As Integer
                'For i = 0 To dt.Rows.Count - 1
                '    Me.hidBOQty.Value &= CStr(dt.Rows(i)("QUANTITY")) & ","
                'Next

                'If Me.hidBOQty.Value.Length > 0 Then
                '    Me.hidBOQty.Value = Me.hidBOQty.Value.Substring(0, Me.hidBOQty.Value.Length - 1)
                'End If

            Else
                Me.trBO.Visible = False
            End If

            If idx < 0 Then
                ' new order item
                'Me.OrderItemIndex = PageBO.AddNewOrderItem
                lblTitle.Text = "Create new Product Item"
            Else
                lblTitle.Text = "Edit Product Item"
                Me.OrderItemIndex = idx
                UpdateData(False)
            End If

        End If
    End Sub

    'check for existing product & color code
    Private Function IsExisting(ByVal idxEdit As Integer) As Boolean
        Dim i As Integer
        If (trBO.Visible = True) Then
            ' use from BO
            Dim oiID As Integer
            Try
                Dim dgi As DataGridItem
                For Each dgi In dgBOItems.Items
                    Dim rad As HtmlInputRadioButton
                    rad = CType(dgi.Cells(0).FindControl("rdbSelected"), HtmlInputRadioButton)

                    If rad.Checked Then
                        oiID = CInt(rad.Value)
                        Exit For
                    End If
                Next
            Catch
            End Try
            Dim objOI As New COrderItem
            objOI.Load(oiID)
            Me.txtColor.Text = objOI.Color
            Me.txtProductCode.Text = objOI.ProductCode
        End If

        For i = 0 To PageBO.OrderItems.Count - 1
            If (i <> idxEdit) _
                And (PageBO.OrderItem(i).ProductCode = Me.txtProductCode.Text) _
                And (PageBO.OrderItem(i).Color = Me.txtColor.Text) Then
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        'If CInt(Request.QueryString("idx")) < 0 Then
        '    ' add new item
        '    If IsExisting() Then
        '        Me.lblStatus.Text = Me.EXISTING_TEXT
        '        Return
        '    Else
        '        Me.OrderItemIndex = PageBO.AddNewOrderItem
        '    End If
        'End If

        ' Check duplicated product (code & color)
        If IsExisting(CInt(Request.QueryString("idx"))) Then
            Me.lblStatus.Text = Me.EXISTING_TEXT
            Return
        End If

        If CInt(Request.QueryString("idx")) < 0 Then
            ' Add new item
            Me.OrderItemIndex = PageBO.AddNewOrderItem
        End If

        UpdateData(True)
        SetReturnValue()
    End Sub

    Private Sub SetReturnValue()
        Dim s As String = ""
        s += String.Format("window.parent.returnValue = {0};", OrderItem.ID)
        s += "window.parent.close();"
        Response.Write(String.Format("<script>{0}</script", s))
    End Sub

    Private Sub BindGrid()
        If trBO.Visible = True Then

            Me.dgBOItems.Visible = True
            Me.trProCode.Visible = False
            Me.trProColor.Visible = False
            Me.trPartofBarCode.Visible = False

            Dim objOrder As New COrder

            Dim selectedValue As Integer
            Try
                selectedValue = CInt(ddlBO.SelectedItem.Value)
                objOrder.Load(selectedValue)
            Catch ex As Exception
                ddlBO.Enabled = False
                For Each ctrl As Control In Page.Controls(0).Controls
                    If (TypeOf ctrl Is System.Web.UI.WebControls.TextBox) Then
                        CType(ctrl, System.Web.UI.WebControls.TextBox).Enabled = False
                    ElseIf (TypeOf ctrl Is System.Web.UI.WebControls.CheckBox) Then
                        CType(ctrl, System.Web.UI.WebControls.CheckBox).Enabled = False
                    ElseIf (TypeOf ctrl Is System.Web.UI.WebControls.DropDownList) Then
                        CType(ctrl, System.Web.UI.WebControls.DropDownList).Enabled = False
                    ElseIf (TypeOf ctrl Is System.Web.UI.WebControls.Button) Then
                        CType(ctrl, System.Web.UI.WebControls.Button).Enabled = False
                    End If
                Next
            End Try

            Me.dgBOItems.DataSource = objOrder.OrderItems
            Me.dgBOItems.DataBind()

            Dim dgi As DataGridItem
            Dim i As Integer
            Dim isChecked As Boolean = False

            For i = 0 To dgBOItems.Items.Count - 1
                dgi = dgBOItems.Items(i)

                Dim rad As HtmlInputRadioButton
                rad = CType(dgi.Cells(0).FindControl("rdbSelected"), HtmlInputRadioButton)

                If CInt(Request.QueryString("idx")) >= 0 Then
                    ' load
                    If rad.Value = OrderItem.UseFromBoItem.ToString Then
                        rad.Checked = True
                        isChecked = True
                        Exit For
                    End If
                End If
            Next

            If (isChecked = False And dgBOItems.Items.Count > 0) Then
                ' default the first radion button is checked
                CType(dgBOItems.Items(0).Cells(0).FindControl("rdbSelected"), HtmlInputRadioButton).Checked = True
            End If
        Else
            Me.dgBOItems.Visible = False
            Me.trProCode.Visible = True
            Me.trProColor.Visible = True
            Me.trPartofBarCode.Visible = True
        End If
    End Sub

    Private Sub ddlBO_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlBO.SelectedIndexChanged
        BindGrid()
    End Sub
End Class
